<template>
  <div>
    <el-select :size="size" class="disabled-select" ref="userSelect" @visible-change="handleOpen" :multiple="multiple" :value="defaultValue" :placeholder="'请'+placeholder">
      <el-option
        v-for="item in selectedData"
        :key="item.userId"
        :label="(item.dept && item.dept.deptName)+' - '+item.nickName+'（'+(item.phonenumber || '暂无手机号')+'）'"
        :value="item.userId">
      </el-option>
    </el-select>
    <el-dialog :title="placeholder" :visible.sync="open" width="1000px" append-to-body>
      <el-row :gutter="20">
        <!--部门数据-->
        <el-col :span="7" :xs="24" v-if="showDept">
          <div class="head-container">
            <el-input
              v-model="deptName"
              placeholder="请输入部门名称"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container dept-tree-scrollbar">
            <el-tree
              :data="deptOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              :accordion="true"
              node-key="id"
              :default-expanded-keys="deptOptions && deptOptions.length?[deptOptions[0].id]:[]"
              ref="tree"
              @node-click="handleNodeClick"
            />
          </div>
        </el-col>
        <!--用户数据-->
        <el-col :span="showDept?17:24" :xs="24">
          <el-table v-loading="loading" height="450px" :data="userList"  row-key="userId" @selection-change="handleSelectionChange">
            <el-table-column v-if="multiple" type="selection" width="50" align="center" :reserve-selection="true"/>
            <el-table-column v-else label="" width="50" align="center">
              <template slot-scope="scope">
                <el-radio class="radio-hide-label" v-model="tableRadio" :label="JSON.stringify(scope.row)" @change="handleSelectionChange"></el-radio>
              </template>
            </el-table-column>
            <el-table-column label="编号" align="center" key="userId" prop="userId" width="70"/>
            <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" />
            <el-table-column label="姓名" align="center" key="nickName" prop="nickName" width="100"/>
            <el-table-column label="电话" align="center" key="phonenumber" prop="phonenumber" width="120" />
            <el-table-column label="身份证号" align="center" key="idCard" prop="idCard" width="170"/>
          </el-table>
          <pagination
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            layout="total, prev, pager, next"
            @pagination="getList"
          />
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirm">确 定</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser } from "@/api/system/user";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "SelectUser",
  components: { Treeselect },
  props: {
    value: [String, Number, Object, Array],
    visible: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: ''
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: '选择用户',
    },
    queryData: {
      type: Object,
      default: ()=>{},
    },
    showDept: {
      type: Boolean,
      default: true,
    }
  },
  data() {
    return {
      defaultValue: '',
      open: false,
      tableRadio: '',
      // 遮罩层
      loading: true,
      // 选中数组
      selectedData: [],
      ids: [],
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 部门树选项
      deptOptions: undefined,
      // 部门名称
      deptName: undefined,
      // 表单参数
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20
      }
    };
  },
  watch: {
    value(nVal, oVal) {
      if(this.multiple){
        this.defaultValue = nVal?nVal.split(',').map(row=>Number(row)):[];
      }else{
        this.defaultValue = nVal?Number(nVal):'';
      }
		},
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    if(this.multiple){
      this.defaultValue = this.value?this.value.split(',').map(row=>Number(row)):[];
    }else{
      this.defaultValue = this.value?Number(this.value):'';
    }
    Object.assign(this.queryParams,this.queryData)
    this.getAllList();
    this.getList();
    this.getTreeselect();
  },
  methods: {
    /** 查询用户列表 */
    getAllList() {
      listUser(Object.assign({ pageNum: 1,pageSize: 200 },this.queryData)).then(response => {
        this.selectedData = response.rows;
      });
    },
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.queryParams.pageNum = 1
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = this.multiple?selection:[JSON.parse(selection)];
    },
    // 选择服务商
    handleOpen() {
      this.$refs.userSelect.blur()
      this.open = true
    },
    close(){
      this.open = false
    },
    confirm(){
      this.selectedData = JSON.parse(JSON.stringify(this.ids))
      if(this.multiple){
        this.defaultValue = this.selectedData.length?this.selectedData.map(row=>row.userId):[];
      }else{
        this.defaultValue = this.selectedData.length?this.selectedData[0].userId:'';
      }
      this.$emit('input', this.multiple?this.defaultValue.join(','):this.defaultValue);
      this.open = false
    }
  }
};
</script>